<template>
    <div class="farm-detail-bg">
        <el-container>
            <el-main class="main-content">
                <!-- 顶部产品信息 -->
                <div class="product-header" style="display: flex; align-items: flex-start;">
                    <div class="product-left" style="display: flex; align-items: flex-start;">
                        <img :src="detail.cover_Image" class="product-img" />
                        <div style="margin-left: 32px;">
                            <div class="product-info">
                                <h2 style="margin-bottom: 24px;">{{ detail.goodsName }}</h2>
                                <div class="info-item">生产批次：{{ detail.production_Batch }}</div>
                                <div class="info-item">保质期：{{ detail.quality_Guarantee }} 天</div>
                                <div class="info-item">生产许可证号：{{ detail.production_License }}</div>
                                <div class="info-item">生产企业：{{ detail.manufacturing_Enterprise }}</div>
                            </div>
                            <div class="report-section" style="margin-top: 24px;">
                                <div class="report-title">产品检验报告</div>
                                <div class="report-content">
                                    <MultiImageUpload v-model="reportImgs" :max-count="5" :upload-text="'上传报告'"
                                        :traceability-id="Number(route.query.traceabilityId)" :disabled="false"
                                        @upload-success="onReportUploadSuccess" @remove="onReportRemove" />

                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- <div class="product-right"
                        style="margin-left: auto; display: flex; flex-direction: column; gap: 12px;">
                        <el-button @click="onEditBasic">修改基本信息</el-button>
                        <el-button @click="onExport">导出溯源码</el-button>
                    </div> -->
                </div>

                <!-- tab页导航 -->
                <el-tabs v-model="activeTab" class="detail-tabs">
                    <el-tab-pane label="养殖信息 (5/5)" name="farming">
                        <FarmingInfo :traceability-id="Number(route.query.traceabilityId)" :farming-info="farmingInfo"
                            :enterprise-info="enterpriseInfo" :certificate-imgs="certificateImgs"
                            :enterprise-photo-imgs="enterprisePhotoImgs" @update:farming-info="updateFarmingInfo"
                            @update:enterprise-info="updateEnterpriseInfo"
                            @update:certificate-imgs="updateCertificateImgs"
                            @update:enterprise-photo-imgs="updateEnterprisePhotoImgs"
                            @certificate-remove="onCertificateRemove"
                            @enterprise-photo-remove="onEnterprisePhotoRemove" />
                    </el-tab-pane>
                    <el-tab-pane label="屠宰信息 (5/5)" name="slaughter">
                        <SlaughterInfo :traceability-id="Number(route.query.traceabilityId)"
                            :slaughter-info="slaughterInfo" :enterprise-info="slaughterEnterpriseInfo"
                            :certificate-imgs="slaughterCertificateImgs"
                            :enterprise-photo-imgs="slaughterEnterprisePhotoImgs"
                            @update:slaughter-info="updateSlaughterInfo"
                            @update:enterprise-info="updateSlaughterEnterpriseInfo"
                            @update:certificate-imgs="updateSlaughterCertificateImgs"
                            @update:enterprise-photo-imgs="updateSlaughterEnterprisePhotoImgs"
                            @certificate-remove="onSlaughterCertificateRemove"
                            @enterprise-photo-remove="onSlaughterEnterprisePhotoRemove" />
                    </el-tab-pane>
                    <el-tab-pane label="深加工信息 (0/5)" name="processing">
                        <ProcessingInfo :traceability-id="Number(route.query.traceabilityId)"
                            :processing-info="processingInfo" :enterprise-info="processingEnterpriseInfo"
                            :food-safety-imgs="processingFoodSafetyImgs" :raw-material-imgs="processingRawMaterialImgs"
                            :auxiliary-material-imgs="processingAuxiliaryMaterialImgs"
                            :additive-imgs="processingAdditiveImgs"
                            :packaging-material-imgs="processingPackagingMaterialImgs"
                            :enterprise-photo-imgs="processingEnterprisePhotoImgs"
                            @update:processing-info="updateProcessingInfo"
                            @update:enterprise-info="updateProcessingEnterpriseInfo"
                            @update:food-safety-imgs="updateProcessingFoodSafetyImgs"
                            @update:raw-material-imgs="updateProcessingRawMaterialImgs"
                            @update:auxiliary-material-imgs="updateProcessingAuxiliaryMaterialImgs"
                            @update:additive-imgs="updateProcessingAdditiveImgs"
                            @update:packaging-material-imgs="updateProcessingPackagingMaterialImgs"
                            @update:enterprise-photo-imgs="updateProcessingEnterprisePhotoImgs"
                            @food-safety-remove="onProcessingFoodSafetyRemove"
                            @raw-material-remove="onProcessingRawMaterialRemove"
                            @auxiliary-material-remove="onProcessingAuxiliaryMaterialRemove"
                            @additive-remove="onProcessingAdditiveRemove"
                            @packaging-material-remove="onProcessingPackagingMaterialRemove"
                            @enterprise-photo-remove="onProcessingEnterprisePhotoRemove" />
                    </el-tab-pane>
                </el-tabs>
                <!-- 修改基本信息弹窗 -->
                <el-dialog v-model="editBasicVisible" title="修改基本信息" width="500px">
                    <el-form :model="basicForm" label-width="120px">
                        <el-form-item label="商品名称：">
                            <el-select v-model="basicForm.goodsId" placeholder="请选择商品名称" style="width: 100%">
                                <el-option v-for="item in data" :key="item.goodsId" :label="item.goodsName"
                                    :value="Number(item.goodsId)" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="生产批次：">
                            <el-input v-model="basicForm.production_Batch" />
                        </el-form-item>
                        <el-form-item label="保质期：">
                            <el-input v-model="basicForm.quality_Guarantee" />
                        </el-form-item>
                        <el-form-item label="生产许可证号：">
                            <el-input v-model="basicForm.production_License" />
                        </el-form-item>
                        <el-form-item label="生产企业：">
                            <el-input v-model="basicForm.manufacturing_Enterprise" />
                        </el-form-item>
                        <el-form-item label="封面图：">
                            <el-upload class="avatar-uploader" :show-file-list="false"
                                :http-request="handleCoverUpload">
                                <img v-if="basicForm.cover_Image" :src="basicForm.cover_Image"
                                    class="avatar avatar-large" />
                                <i v-else class="el-icon-plus avatar-uploader-icon avatar-large" />
                            </el-upload>
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <el-button @click="editBasicVisible = false">取消</el-button>
                        <el-button type="primary" @click="saveBasicInfo">保存</el-button>
                    </template>
                </el-dialog>

                <!-- 导出弹窗 -->
                <el-dialog v-model="exportDialogVisible" title="导出设置" width="400px" :close-on-click-modal="false">
                    <el-form label-width="100px">
                        <el-form-item label="导出数量：">
                            <el-input-number v-model="exportCount" :min="1" :max="9999" />
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <el-button @click="exportDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="doExport">导出</el-button>
                    </template>
                </el-dialog>
            </el-main>
        </el-container>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Read, Write } from '@/components/Http/axiosHepler';
import { useRouter, useRoute } from 'vue-router';
import MultiImageUpload from '@/components/MultiImageUpload.vue';
import FarmingInfo from '@/components/FarmingInfo.vue';
import SlaughterInfo from '@/components/SlaughterInfo.vue';
import ProcessingInfo from '@/components/ProcessingInfo.vue';

import axios from 'axios';
import { useCounterStore } from "@/stores/counter";

const router = useRouter();
const route = useRoute();
const store = useCounterStore();
const activeTab = ref('farming');
const editBasicVisible = ref(false);
const exportDialogVisible = ref(false);
const exportCount = ref(1);

// 产品详情数据
const detail = reactive({
    cover_Image: '',
    goodsId: '',
    goodsName: '',
    production_Batch: '',
    quality_Guarantee: '',
    production_License: '',
    manufacturing_Enterprise: '',
    reportImg: '',
    certificateImg: '',
    enterprisePhotos: ''
});

// 养殖信息
const farmingInfo = reactive({
    breed: '',
    feedingDays: '',
    manager: '',
    source: '',
    feedBrand: ''
});

// 企业信息
const enterpriseInfo = reactive({
    farm: '四川锦祥养殖基地',
    manager: 'X总',
    stockQuantity: '3200'
});

// 企业照片图片数组
const enterprisePhotoImgs = ref<string[]>([]);
// 动检证图片数组
const certificateImgs = ref<string[]>([]);
// 产品检验报告图片数组
const reportImgs = ref<string[]>([]);

// 屠宰信息相关数据
const slaughterInfo = reactive({
    slaughterId: '',
    slaughter_Date: '',
    slaughter_Quantity: '',
    slaughter_Supervisor: '',
    slaughter_Method: '',
    slaughter_Equipment: '',
    slaughter_Address: '',
    traceabilityId: ''
});

const slaughterEnterpriseInfo = reactive({
    slaughter_House: '',
    slaughter_Manager: '',
    license_Number: ''
});

const slaughterCertificateImgs = ref<string[]>([]);
const slaughterEnterprisePhotoImgs = ref<string[]>([]);

// 深加工信息相关数据
const processingInfo = reactive({
    processingId: '',
    batch_No: '',
    processing_Date: '',
    processing_Quantity: '',
    processing_Technology: '',
    processing_Temperature: '',
    processing_Time: '',
    quality_Grade: '',
    processing_Supervisor: '',
    traceabilityId: ''
});

const processingEnterpriseInfo = reactive({
    corporate_Name: '',
    province: '',
    ocation_City: '',
    detailed_Addres: '',
    establishment_Date: '',
    company_Profile: ''
});

const processingFoodSafetyImgs = ref<string[]>([]);
const processingRawMaterialImgs = ref<string[]>([]);
const processingAuxiliaryMaterialImgs = ref<string[]>([]);
const processingAdditiveImgs = ref<string[]>([]);
const processingPackagingMaterialImgs = ref<string[]>([]);
const processingCertificateImgs = ref<string[]>([]);
const processingEnterprisePhotoImgs = ref<string[]>([]);

// 基本信息表单
const basicForm = reactive({
    goodsId: '' as number | string,
    production_Batch: '',
    quality_Guarantee: '',
    production_License: '',
    manufacturing_Enterprise: '',
    cover_Image: ''
});

// 获取溯源信息
const GetTraceability = () => {
    Read.get("/Management/TraceabilityFind", {
        params: {
            traceabilityId: route.query.traceabilityId
        }
    }).then(res => {
        console.log('获取溯源信息响应:', res.data);
        if (res.data.code === 200 && res.data.data && res.data.data[0]) {
            Object.assign(detail, res.data.data[0]);
            console.log('更新后的detail:', detail);

            // 获取图片数据
            GetPictureData();
        }
    }).catch(err => {
        console.error('获取溯源信息失败:', err);
        ElMessage.error('获取溯源信息失败: ' + (err?.response?.data?.message || err?.message || '未知错误'));
    });
}

// 获取图片数据
const GetPictureData = async () => {
    try {
        console.log('正在获取图片数据，traceabilityId:', route.query.traceabilityId);
        console.log('API地址: https://localhost:7120/api/Image/PictureShow');
        console.log('完整请求URL:', `https://localhost:7120/api/Image/PictureShow?TraceabilityId=${route.query.traceabilityId}`);

        const res = await Read.get("/Image/PictureShow", {
            params: {
                TraceabilityId: route.query.traceabilityId
            }
        });

        console.log('获取图片数据响应:', res.data);
        console.log('实际请求URL:', res.config.url);

        if (res.data.code === 200 && res.data.data && res.data.data.length > 0) {
            const pictureData = res.data.data[0];
            console.log('=== 图片数据调试信息 ===');
            console.log('完整图片数据对象:', pictureData);
            console.log('图片数据字段列表:', Object.keys(pictureData));
            console.log('深加工相关字段值:');
            console.log('- Food_Safety:', pictureData.Food_Safety);
            console.log('- Raw_Material:', pictureData.Raw_Material);
            console.log('- Auxiliary_Materials:', pictureData.Auxiliary_Materials);
            console.log('- Additive_Materials:', pictureData.Additive_Materials);
            console.log('- Packaging_Materials:', pictureData.Packaging_Materials);
            console.log('- Enterprise_Image:', pictureData.Enterprise_Image);
            console.log('=== 调试信息结束 ===');
            console.log('图片数据:', pictureData);

            // 更新detail中的图片字段
            if (pictureData.inspection_Repor) {
                detail.reportImg = pictureData.inspection_Repor;
                console.log('设置detail.reportImg:', detail.reportImg);
            } else {
                detail.reportImg = '';
                console.log('清空detail.reportImg');
            }
            if (pictureData.livestock_Certification) {
                detail.certificateImg = pictureData.livestock_Certification;
                console.log('设置detail.certificateImg:', detail.certificateImg);
            } else {
                detail.certificateImg = '';
                console.log('清空detail.certificateImg');
            }
            if (pictureData.certification_Documents) {
                detail.enterprisePhotos = pictureData.certification_Documents;
                console.log('设置detail.enterprisePhotos:', detail.enterprisePhotos);
            } else {
                detail.enterprisePhotos = '';
                console.log('清空detail.enterprisePhotos');
            }

            // 处理屠宰信息图片数据
            if (pictureData.food_Safety) {
                console.log('设置屠宰证书图片:', pictureData.food_Safety);
                const slaughterCertificateUrls = pictureData.food_Safety.includes(',')
                    ? pictureData.food_Safety.split(',').filter((url: string) => url && url.trim())
                    : [pictureData.food_Safety];
                slaughterCertificateImgs.value = slaughterCertificateUrls;
            } else {
                console.log('清空屠宰证书图片');
                slaughterCertificateImgs.value = [];
            }

            if (pictureData.certification_Documents) {
                console.log('设置屠宰企业照片:', pictureData.certification_Documents);
                const slaughterEnterprisePhotoUrls = pictureData.certification_Documents.includes(',')
                    ? pictureData.certification_Documents.split(',').filter((url: string) => url && url.trim())
                    : [pictureData.certification_Documents];
                slaughterEnterprisePhotoImgs.value = slaughterEnterprisePhotoUrls;
            } else {
                console.log('清空屠宰企业照片');
                slaughterEnterprisePhotoImgs.value = [];
            }

            // 处理深加工信息图片数据 - 使用实际的数据库字段名（小写）
            if (pictureData.enterprise_Image) {
                console.log('设置深加工食品安全图片:', pictureData.enterprise_Image);
                const processingFoodSafetyUrls = pictureData.enterprise_Image.includes(',')
                    ? pictureData.enterprise_Image.split(',').filter((url: string) => url && url.trim())
                    : [pictureData.enterprise_Image];
                processingFoodSafetyImgs.value = processingFoodSafetyUrls;
            } else {
                console.log('清空深加工食品安全图片');
                processingFoodSafetyImgs.value = [];
            }

            if (pictureData.raw_Material) {
                console.log('设置深加工原料图片:', pictureData.raw_Material);
                const processingRawMaterialUrls = pictureData.raw_Material.includes(',')
                    ? pictureData.raw_Material.split(',').filter((url: string) => url && url.trim())
                    : [pictureData.raw_Material];
                processingRawMaterialImgs.value = processingRawMaterialUrls;
            } else {
                console.log('清空深加工原料图片');
                processingRawMaterialImgs.value = [];
            }

            if (pictureData.auxiliary_Materials) {
                console.log('设置深加工辅料图片:', pictureData.auxiliary_Materials);
                const processingAuxiliaryMaterialUrls = pictureData.auxiliary_Materials.includes(',')
                    ? pictureData.auxiliary_Materials.split(',').filter((url: string) => url && url.trim())
                    : [pictureData.auxiliary_Materials];
                processingAuxiliaryMaterialImgs.value = processingAuxiliaryMaterialUrls;
            } else {
                console.log('清空深加工辅料图片');
                processingAuxiliaryMaterialImgs.value = [];
            }

            if (pictureData.additive_Materials) {
                console.log('设置深加工添加剂图片:', pictureData.additive_Materials);
                const processingAdditiveUrls = pictureData.additive_Materials.includes(',')
                    ? pictureData.additive_Materials.split(',').filter((url: string) => url && url.trim())
                    : [pictureData.additive_Materials];
                processingAdditiveImgs.value = processingAdditiveUrls;
            } else {
                console.log('清空深加工添加剂图片');
                processingAdditiveImgs.value = [];
            }

            if (pictureData.packaging_Materials) {
                console.log('设置深加工包装材料图片:', pictureData.packaging_Materials);
                const processingPackagingMaterialUrls = pictureData.packaging_Materials.includes(',')
                    ? pictureData.packaging_Materials.split(',').filter((url: string) => url && url.trim())
                    : [pictureData.packaging_Materials];
                processingPackagingMaterialImgs.value = processingPackagingMaterialUrls;
            } else {
                console.log('清空深加工包装材料图片');
                processingPackagingMaterialImgs.value = [];
            }

            if (pictureData.certification_Documents) {
                console.log('设置深加工企业照片:', pictureData.certification_Documents);
                const processingEnterprisePhotoUrls = pictureData.certification_Documents.includes(',')
                    ? pictureData.certification_Documents.split(',').filter((url: string) => url && url.trim())
                    : [pictureData.certification_Documents];
                processingEnterprisePhotoImgs.value = processingEnterprisePhotoUrls;
            } else {
                console.log('清空深加工企业照片');
                processingEnterprisePhotoImgs.value = [];
            }

            // 输出所有深加工图片数组的最终状态
            console.log('=== 深加工图片数组最终状态 ===');
            console.log('processingFoodSafetyImgs:', processingFoodSafetyImgs.value);
            console.log('processingRawMaterialImgs:', processingRawMaterialImgs.value);
            console.log('processingAuxiliaryMaterialImgs:', processingAuxiliaryMaterialImgs.value);
            console.log('processingAdditiveImgs:', processingAdditiveImgs.value);
            console.log('processingPackagingMaterialImgs:', processingPackagingMaterialImgs.value);
            console.log('processingEnterprisePhotoImgs:', processingEnterprisePhotoImgs.value);
            console.log('=== 深加工图片数组状态结束 ===');

            // 同步图片数组
            syncImageArrays();
            console.log('图片数据同步完成');
        } else {
            console.log('没有找到图片数据，清空显示');
            // 清空图片数据
            detail.reportImg = '';
            detail.certificateImg = '';
            detail.enterprisePhotos = '';
            // 清空屠宰信息图片数据
            slaughterCertificateImgs.value = [];
            slaughterEnterprisePhotoImgs.value = [];
            // 清空深加工信息图片数据
            processingFoodSafetyImgs.value = [];
            processingRawMaterialImgs.value = [];
            processingAuxiliaryMaterialImgs.value = [];
            processingAdditiveImgs.value = [];
            processingPackagingMaterialImgs.value = [];
            processingEnterprisePhotoImgs.value = [];
            syncImageArrays();
        }
    } catch (err) {
        console.error('获取图片数据失败:', err);
        // 获取失败时，清空图片数据
        console.log('获取图片数据失败，清空显示');
        detail.reportImg = '';
        detail.certificateImg = '';
        detail.enterprisePhotos = '';
        // 清空屠宰信息图片数据
        slaughterCertificateImgs.value = [];
        slaughterEnterprisePhotoImgs.value = [];
        // 清空深加工信息图片数据
        processingFoodSafetyImgs.value = [];
        processingRawMaterialImgs.value = [];
        processingAuxiliaryMaterialImgs.value = [];
        processingAdditiveImgs.value = [];
        processingPackagingMaterialImgs.value = [];
        processingEnterprisePhotoImgs.value = [];
        syncImageArrays();
    }
}

// 修改基本信息
function onEditBasic() {
    Object.assign(basicForm, detail);
    if (detail.goodsId !== undefined && detail.goodsId !== null && detail.goodsId !== '') {
        basicForm.goodsId = Number(detail.goodsId);
    } else {
        basicForm.goodsId = '';
    }
    editBasicVisible.value = true;
}

function saveBasicInfo() {
    Write.post('/Management/TraceabilityUpdate', {
        traceabilityId: Number(route.query.traceabilityId),
        goodsId: Number(basicForm.goodsId),
        production_Batch: basicForm.production_Batch,
        quality_Guarantee: Number(basicForm.quality_Guarantee),
        production_License: basicForm.production_License,
        manufacturing_Enterprise: basicForm.manufacturing_Enterprise,
        cover_Image: basicForm.cover_Image
    }).then(res => {
        if (res.data.code == 200) {
            ElMessage.success('修改成功');
            editBasicVisible.value = false;
            GetTraceability();
        } else {
            ElMessage.error('修改失败');
        }
    }).catch(err => {
        ElMessage.error('修改失败: ' + (err?.response?.data?.message || err?.message || '未知错误'));
    });
}

function doExport() {
    Write.get('/Management/ExportTraceability', {
        params: {
            traceabilityId: route.query.traceabilityId,
            numberOfExports: exportCount.value
        }
    }).then(res => {
        if (typeof res.data === 'string' && res.data.startsWith('http')) {
            ElMessage.success('导出成功，正在下载...');
            window.open(res.data, '_blank');
            exportDialogVisible.value = false;
            return;
        }
        if (typeof res.data === 'string' && res.data.includes('TraceabilityId')) {
            ElMessage.success('导出成功，已生成数据');
            const blob = new Blob([res.data], { type: 'text/csv' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'traceability.csv';
            a.click();
            window.URL.revokeObjectURL(url);
            exportDialogVisible.value = false;
            return;
        }
        if (res.data && res.data.code === 200) {
            ElMessage.success(res.data.message || '导出成功');
            exportDialogVisible.value = false;
        } else {
            ElMessage.error(res.data.message || '导出失败');
        }
    }).catch(err => {
        ElMessage.error('导出失败: ' + (err?.response?.data?.message || err?.message || '未知错误'));
    });
}

// 上传图片（封面图）
const handleCoverUpload = async (option: any) => {
    // 使用阿里云上传方法
    const formData = new FormData();
    formData.append('file', option.file);

    try {
        const response = await axios.post('https://localhost:7273/api/Image/UploadToQiniuOss/uploadToQiniu', formData, {
            headers: {
                'Content-Type': 'multipart/form-data',
                'Authorization': 'Bearer ' + store.CurrentLogin.token
            }
        });

        console.log('图片上传返回：', response.data);
        if (response.data.success === true) {
            basicForm.cover_Image = response.data.data.imageUrl;
            console.log('设置封面图URL:', basicForm.cover_Image);
            option.onSuccess && option.onSuccess(response.data, option.file);
        } else {
            option.onError && option.onError(new Error(response.data.message || '上传失败'));
        }
    } catch (error) {
        console.error('图片上传失败:', error);
        option.onError && option.onError(error);
    }
};

// 产品检验报告图片上传事件处理
const onReportUploadSuccess = async (image: any) => {
    console.log('产品检验报告上传成功:', image);

    // 图片已经通过 uploadHelper.ts 保存到数据库
    // 这里只需要更新本地显示
    if (image && image.url) {
        // 重新获取图片数据以确保同步
        setTimeout(() => {
            GetPictureData();
        }, 500);
    }
};

// 产品检验报告删除处理
const onReportRemove = (index: number, image: any) => {
    console.log('产品检验报告删除事件触发:', index, image);

    // 删除操作已经在 MultiImageUpload 组件中处理
    // 这里只需要记录删除事件，不需要额外处理
    console.log('产品检验报告删除完成');
};

// 动检证删除处理
const onCertificateRemove = (index: number, image: any) => {
    console.log('动检证删除事件触发:', index, image);

    // 删除操作已经在 MultiImageUpload 组件中处理
    // 这里只需要记录删除事件，不需要额外处理
    console.log('动检证删除完成');
};

// 企业照片删除处理
const onEnterprisePhotoRemove = (index: number, image: any) => {
    console.log('企业照片删除事件触发:', index, image);

    // 删除操作已经在 MultiImageUpload 组件中处理
    // 这里只需要记录删除事件，不需要额外处理
    console.log('企业照片删除完成');
};



// 子组件数据更新处理
const updateFarmingInfo = (newInfo: any) => {
    Object.assign(farmingInfo, newInfo);
};

const updateEnterpriseInfo = (newInfo: any) => {
    Object.assign(enterpriseInfo, newInfo);
};

const updateCertificateImgs = (newImgs: string[]) => {
    certificateImgs.value = newImgs;
};

const updateEnterprisePhotoImgs = (newImgs: string[]) => {
    enterprisePhotoImgs.value = newImgs;
};

// 屠宰信息相关更新函数
const updateSlaughterInfo = (newInfo: any) => {
    Object.assign(slaughterInfo, newInfo);
};

const updateSlaughterEnterpriseInfo = (newInfo: any) => {
    Object.assign(slaughterEnterpriseInfo, newInfo);
};

const updateSlaughterCertificateImgs = (newImgs: string[]) => {
    slaughterCertificateImgs.value = newImgs;
};

const updateSlaughterEnterprisePhotoImgs = (newImgs: string[]) => {
    slaughterEnterprisePhotoImgs.value = newImgs;
};

// 深加工信息相关更新函数
const updateProcessingInfo = (newInfo: any) => {
    Object.assign(processingInfo, newInfo);
};

const updateProcessingEnterpriseInfo = (newInfo: any) => {
    Object.assign(processingEnterpriseInfo, newInfo);
};

const updateProcessingFoodSafetyImgs = (newImgs: string[]) => {
    processingFoodSafetyImgs.value = newImgs;
};

const updateProcessingRawMaterialImgs = (newImgs: string[]) => {
    processingRawMaterialImgs.value = newImgs;
};

const updateProcessingAuxiliaryMaterialImgs = (newImgs: string[]) => {
    processingAuxiliaryMaterialImgs.value = newImgs;
};

const updateProcessingAdditiveImgs = (newImgs: string[]) => {
    processingAdditiveImgs.value = newImgs;
};

const updateProcessingPackagingMaterialImgs = (newImgs: string[]) => {
    processingPackagingMaterialImgs.value = newImgs;
};

const updateProcessingEnterprisePhotoImgs = (newImgs: string[]) => {
    processingEnterprisePhotoImgs.value = newImgs;
};

// 屠宰信息删除处理
const onSlaughterCertificateRemove = (index: number, image: any) => {
    console.log('屠宰证书删除事件触发:', index, image);
    console.log('屠宰证书删除完成');
};

const onSlaughterEnterprisePhotoRemove = (index: number, image: any) => {
    console.log('屠宰企业照片删除事件触发:', index, image);
    console.log('屠宰企业照片删除完成');
};

// 深加工信息删除处理
const onProcessingFoodSafetyRemove = (index: number, image: any) => {
    console.log('深加工证书删除事件触发:', index, image);
    console.log('深加工证书删除完成');
};

const onProcessingRawMaterialRemove = (index: number, image: any) => {
    console.log('深加工原料删除事件触发:', index, image);
    console.log('深加工原料删除完成');
};

const onProcessingAuxiliaryMaterialRemove = (index: number, image: any) => {
    console.log('深加工辅料删除事件触发:', index, image);
    console.log('深加工辅料删除完成');
};

const onProcessingAdditiveRemove = (index: number, image: any) => {
    console.log('深加工添加剂删除事件触发:', index, image);
    console.log('深加工添加剂删除完成');
};

const onProcessingPackagingMaterialRemove = (index: number, image: any) => {
    console.log('深加工包装材料删除事件触发:', index, image);
    console.log('深加工包装材料删除完成');
};

const onProcessingEnterprisePhotoRemove = (index: number, image: any) => {
    console.log('深加工企业照片删除事件触发:', index, image);
    console.log('深加工企业照片删除完成');
};

// 页面初始化时同步图片数组
const syncImageArrays = () => {
    console.log('开始同步图片数组...');
    console.log('当前detail.reportImg:', detail.reportImg);
    console.log('当前reportImgs:', reportImgs.value);

    // 同步动检证图片
    if (detail.certificateImg && detail.certificateImg.trim()) {
        const newCertificateImgs = detail.certificateImg.includes(',')
            ? detail.certificateImg.split(',').filter((url: string) => url && url.trim())
            : [detail.certificateImg];
        console.log('同步动检证图片:', newCertificateImgs);
        certificateImgs.value = newCertificateImgs;
    } else {
        certificateImgs.value = [];
        console.log('清空动检证图片');
    }

    // 同步企业照片
    if (detail.enterprisePhotos && detail.enterprisePhotos.trim()) {
        const newEnterprisePhotos = detail.enterprisePhotos.includes(',')
            ? detail.enterprisePhotos.split(',').filter((url: string) => url && url.trim())
            : [detail.enterprisePhotos];
        console.log('同步企业照片:', newEnterprisePhotos);
        enterprisePhotoImgs.value = newEnterprisePhotos;
    } else {
        enterprisePhotoImgs.value = [];
        console.log('清空企业照片');
    }

    // 同步产品检验报告图片
    if (detail.reportImg && detail.reportImg.trim()) {
        // 如果是单个URL，转换为数组
        const newReportImgs = detail.reportImg.includes(',')
            ? detail.reportImg.split(',').filter((url: string) => url && url.trim())
            : [detail.reportImg];

        console.log('同步产品检验报告图片:', newReportImgs);
        reportImgs.value = newReportImgs;
    } else {
        console.log('清空产品检验报告图片');
        reportImgs.value = [];
    }

    // 同步深加工信息图片数组
    console.log('=== 同步深加工信息图片数组 ===');
    console.log('processingFoodSafetyImgs:', processingFoodSafetyImgs.value);
    console.log('processingRawMaterialImgs:', processingRawMaterialImgs.value);
    console.log('processingAuxiliaryMaterialImgs:', processingAuxiliaryMaterialImgs.value);
    console.log('processingAdditiveImgs:', processingAdditiveImgs.value);
    console.log('processingPackagingMaterialImgs:', processingPackagingMaterialImgs.value);
    console.log('processingEnterprisePhotoImgs:', processingEnterprisePhotoImgs.value);
    console.log('=== 深加工信息图片数组同步完成 ===');

    console.log('图片数组同步完成');
};

const data = ref<any[]>([]);
const ShopShow = () => {
    Read.get("/Management/GoodShow").then(res => {
        if (res.data.code === 200 && res.data.data) {
            data.value = res.data.data.map((item: any) => ({
                ...item,
                goodsId: Number(item.goodsId)
            }));
        }
    }).catch(err => {
        console.error('获取商品列表失败:', err);
        ElMessage.error('获取商品列表失败: ' + (err?.response?.data?.message || err?.message || '未知错误'));
    });
}

onMounted(() => {
    try {
        GetTraceability();
        ShopShow();
    } catch (error) {
        console.error('页面初始化失败:', error);
        ElMessage.error('页面初始化失败，请刷新重试');
    }
});
</script>

<style scoped>
.farm-detail-bg {
    background: #f5f7fa;
    min-height: 100vh;
}

.main-content {
    padding: 24px;
}

.product-header {
    background: #fff;
    border-radius: 8px;
    padding: 24px;
    margin-bottom: 24px;
}

.product-img {
    width: 80px;
    height: 80px;
    border-radius: 8px;
    object-fit: cover;
}

.product-info {
    display: flex;
    flex-direction: column;
    gap: 8px;
    margin-bottom: 0;
}

.info-item {
    margin-bottom: 8px;
    color: #606266;
}

.report-section {
    text-align: center;
}

.report-title {
    margin-bottom: 8px;
    color: #606266;
}

.report-content {
    display: flex;
    align-items: center;
    gap: 16px;
}

.detail-tabs {
    background: #fff;
    border-radius: 8px;
    padding: 24px;
}

.avatar {
    width: 100%;
    height: 80px;
    display: block;
    border-radius: 6px;
    object-fit: cover;
    border: 2px solid #222;
}

.avatar-large {
    width: 120px;
    height: 120px;
    margin: 0 auto;
    display: block;
    object-fit: cover;
}

.avatar-uploader {
    width: 80px;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 2px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    background: #fff;
}

.avatar-uploader-icon {
    font-size: 32px;
    color: #8c939d;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
}
</style>
